<template>
  <van-button
    :icon="isCollect ? 'star' : 'star-o'"
    :style="{ color: isCollect ? '#ffa500' : '#777' }"
    :loading="isLoading"
    @click="collectFn"
  ></van-button>
</template>

<script>
import { addCollect, deleteCollect } from "@/api/article.js";
export default {
  data() {
    return {
      isLoading: false, //收藏状态
    };
  },
  model: {
    prop: "isCollect",
    event: "updated-isCollect",
  },
  props: {
    isCollect: {
      type: Boolean,
      required: true,
    },
    artId: {
      type: [Number, String],
      required: true,
    },
  },
  methods: {
    async collectFn() {
      // 点击收藏开启收藏中状态
      this.isLoading = true;
      try {
        // 是否收藏 收藏了就发送取消收藏
        if (this.isCollect) {
          await deleteCollect(this.artId);
        } else {
          await addCollect(this.artId);
        }
        this.$emit("updated-isCollect", !this.isCollect);
        this.$toast.success(!this.isCollect ? "收藏成功" : "取消收藏");
      } catch (err) {
        let message = "操作失败请稍等重试";
        if (err.response && err.response.status) {
          switch (err.response.status) {
            case 400:
              message = "自己不能关注自己";
              break;
            case 401:
              message = "用户未认证";
              break;
            case 507:
              message = "数据库错误";
              break;
          }
        }
        this.$toast.fail(message);
      }
      // 请求完毕关闭收藏中状态
      this.isLoading = false;
    },
  },
};
</script>

<style scoped>
</style>